<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        // 数组扁平化
        let arr = [1, [2, 3]]
        console.log(arr.flat())
        let a = [1, [2, 3, [4, 5, [6]]]]
        console.log(a.flat(Infinity))
        // 1、concat实现
        function flatten(arr) {
            let result = []
            for (let i = 0; i < arr.length; i++) {
                if (Array.isArray(arr[i])) {
                    result = result.concat(flatten(arr[i]))
                } else {
                    result.push(arr[i])
                }
            }
            return result
        }
        console.log(flatten(a))
        // 2、reduce实现
        function flatten2(arr) {
            return arr.reduce((prev, cur) => {
                return prev.concat(Array.isArray(cur) ? flatten2(cur) : cur)
            }, [])
        }
        console.log(flatten2(a))
        // 3、指定deep
        function flat(arr, deep) {
            let res = []
            for (let i in arr) {
                if (Array.isArray(arr[i]) && deep) {
                    res = res.concat(flat(arr[i], deep - 1))
                } else {
                    res.push(arr[i])
                }
            }
            return res
        }
        console.log(flat([12, [1, 2, 3], 3, [2, 4, [4, [3, 4], 2]]], 1));
    </script>
</body>

</html>